package br.com.cast.scc.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.Session;

import br.com.cast.scc.model.IEntidade;

public class BaseDAO<T extends IEntidade> {
	
	@PersistenceContext(unitName = "persistencia")
	private EntityManager entityManager;
	
	protected EntityManager getEntityManager(){
		return this.entityManager;
	}
	
	protected Session getHibernateCurrentSession() {
		return (Session) getEntityManager().getDelegate();
	}
	
	
	public void salvar(T entidade){
		getEntityManager().persist(entidade);
	}
	
	public void alterar(T entidade){
		getEntityManager().merge(entidade);
	}
	
	@SuppressWarnings("unchecked")
	public void excluir(T entidade){
		entidade = (T) getHibernateCurrentSession()
						.get(entidade.getClass(), entidade.getCodigo());
		getEntityManager().remove(entidade);
	}
	
	public long total(Class<T> classe){
		StringBuilder hql = new StringBuilder();
		
		hql.append("SELECT COUNT(*) AS total ")
		   .append(" FROM ")
		   .append(classe.getName());
		
		Query consulta = getEntityManager().createQuery(hql.toString());
		
		return (long) consulta.getSingleResult();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> consultaTodos(Class<T> classe){
		String hql = " FROM " + classe.getName();
		
		return getEntityManager().createQuery(hql).getResultList();
	}
}
